package cn.com.callback

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;

import com.alibaba.fastjson.JSONObject
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import groovy.json.*;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;

/*
 * @purpose: 腾讯云短信发送接口
 * @示例报文：
 * */

public class BP_TencentCloudSendMsg implements ServiceBackInvoke{
	
	private static final Log log=LogFactory.getLog(BP_TencentCloudSendMsg.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){
		log.debug("----------------------------------start BP_TencentCloudSendMsg from 开始发送短信 -----------------------------");//日志标识，方便查找
		boolean sendMsgResult=false; //短信发送结果
		String cloudResponseStr=""; //腾讯云返回结果
		def returnMessage='';//返回信息
		//获取httppost入参
		request.setCharacterEncoding("utf-8");//防止中文乱码
		response.setCharacterEncoding("utf-8");
		def requestBody =Util.getRequestBody(request,"utf-8"); //固定写法
		requestBody=eliteBean.formatString(requestBody);
		log.info( "请求报文--requestBody:"+requestBody);//打印到日志文件中
		def returnDealFlag="";//响应标识 1 成功，0 失败
		def returnDealMessage="";//响应信息
		String documentOutGUID="";//documentout表，主键，用于更新数据

		int templateId=0;////腾讯云短信模板ID
		templateId=680764;
		def mapRequestBody="";
		def jsonSlurper = new JsonSlurper();
		//mapRequestBody = jsonSlurper.parseText(requestBody);
		//templateId = Integer.parseInt(mapRequestBody.data.templateId);  //腾讯云短信模板ID

		if( 680764 == templateId ){
		try{
			//获取到是Map对象
			//documentOutGUID = mapRequestBody.guid;  //documentout表，主键，用于更新数据
			String phoneNumber ="14795766059";//= mapRequestBody.phoneNumber; //获取手机号
			String msg_1 ="001"; //内容参数1 
			
			int appid = 1400407065; // 1400开头 短信应用SDK AppID
			String appkey = "6a3cb1e7fa20ff35444331f2cb90635a";// 短信应用SDK AppKey
			String smsSign = "宝安排水"; // 签名			
				
				//拼接第三个参数
				def msg_final="您好，您投诉/建议的"+msg_1+"案件经我司工作人员现场勘查确认，该案件不属我司管养范围，我们已将该案件移交给相关单位处理。";
				
				ArrayList<?> docParams = new ArrayList<?>();
				docParams.add(msg_1);
				//参数顺序不能乱---   投保人{1}，车牌{2}，总保费：{3}。
				//				ArrayList<?> docParams = new ArrayList<?>();
				//				docParams.add(msg_insuredname);
				//				docParams.add(msg_carplate);
				//				docParams.add(msg_totalmoney);
				//				docParams.add(msg_shorturl);

				//def docParams=new String[2];
				//docParams[0]=msg_1;
				//docParams[1]=msg_final;

				log.info("docParams:"+docParams);
				
				if (!StringUtils.isBlank(appkey) && !StringUtils.isBlank(smsSign) && !StringUtils.isBlank(String.valueOf(appid))) {
					try {
						
						SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
						// 签名参数未提供或者为空时，会使用默认签名发送短信
						SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber, templateId, docParams, smsSign, "", "");
						log.info("result:"+result);

						cloudResponseStr=result.toString();

						JSONObject reponseBodyJsonObject = JSONObject.parseObject(cloudResponseStr);
						String resultCode = reponseBodyJsonObject.getString("result");
						String resultMsg = reponseBodyJsonObject.getString("errmsg");

						if("0".equals(resultCode)) {
							sendMsgResult=true;
							returnDealMessage="腾讯云短信发送成功！";
						} else {
							sendMsgResult=false;
							returnDealMessage="腾讯云短信发送失败！"+java.net.URLDecoder.decode(resultMsg);
						}
					} catch (HTTPException e) {
						// HTTP响应码错误
						sendMsgResult=false;
						returnDealMessage="HTTP响应码错误!";
						e.printStackTrace();
					} catch (JSONException e) {
						// json解析错误
						sendMsgResult=false;
						returnDealMessage="json解析错误!";
						e.printStackTrace();
					} catch (IOException e) {
						// 网络IO错误
						sendMsgResult=false;
						returnDealMessage="网络IO错误!";
						e.printStackTrace();
					}
				}
			
		} catch(SAXParseException) {
			log.error("异常",SAXParseException); //打印日志
			returnDealFlag="0";
			returnDealMessage="电销系统:接收的请求报文格式错误,无法解析数据!";
		}
		if(sendMsgResult) {
			returnDealFlag="1";

		}else {
			returnDealFlag="0";
		}
}
		returnMessage="""{"dealFlag":"${returnDealFlag}","dealMessage":"${returnDealMessage}","cloudResponse":${cloudResponseStr}}""";

		//String sql = """update DocumentOut set cloud_templateid='${templateId}',request_msg='${requestBody}',response_msg='${returnMessage}',Status=${returnDealFlag},TrialCount=TrialCount+1,LastTryDateTime=now(),FinishDateTime=now(),ModifiedDate=now() where DocumentOut_GUID='${documentOutGUID}'""";
		//int i = eliteBean.update(sql,"dataSource");
		//log.info("update=" + i);

		return returnMessage;
	}

}
